package web

import (
	"errors"
	"go-quick/interface/iweb"
	"strconv"
)

// RequestParam 参数
type RequestParam struct {
	params iweb.IRouterParams
}

func NewRequestParam(params iweb.IRouterParams) *RequestParam {
	return &RequestParam{
		params: params,
	}
}

func (q *RequestParam) DefaultParam(key string, value string) {
	q.params.Set(key, value)
}

func (q *RequestParam) ParamString(key string) (value string, err error) {
	value, exist := q.params.Get(key)
	if !exist {
		return "", errors.New("not exist")
	}
	return value, nil
}

func (q *RequestParam) ParamInt(key string) (value int, err error) {
	var (
		val string
	)
	if val, err = q.ParamString(key); err != nil {
		return 0, err
	}
	return strconv.Atoi(val)
}

func (q *RequestParam) ParamInt8(key string) (value int8, err error) {
	var (
		val1 string
		val2 int64
	)
	if val1, err = q.ParamString(key); err != nil {
		return 0, err
	}
	if val2, err = strconv.ParseInt(val1, 10, 8); err != nil {
		return 0, err
	}
	return int8(val2), nil
}

func (q *RequestParam) ParamInt32(key string) (value int32, err error) {
	var (
		val1 string
		val2 int64
	)
	if val1, err = q.ParamString(key); err != nil {
		return 0, err
	}
	if val2, err = strconv.ParseInt(val1, 10, 8); err != nil {
		return 0, err
	}
	return int32(val2), nil
}

func (q *RequestParam) ParamInt64(key string) (value int64, err error) {
	var (
		val1 string
	)
	if val1, err = q.ParamString(key); err != nil {
		return 0, err
	}
	if value, err = strconv.ParseInt(val1, 10, 8); err != nil {
		return 0, err
	}
	return
}

func (q *RequestParam) ParamFloat32(key string) (value float32, err error) {
	var (
		val1 string
		val2 float64
	)
	if val1, err = q.ParamString(key); err != nil {
		return 0, err
	}
	if val2, err = strconv.ParseFloat(val1, 32); err != nil {
		return 0, err
	}
	return float32(val2), nil
}

func (q *RequestParam) ParamFloat64(key string) (value float64, err error) {
	var (
		val1 string
	)
	if val1, err = q.ParamString(key); err != nil {
		return 0, err
	}
	if value, err = strconv.ParseFloat(val1, 64); err != nil {
		return 0, err
	}
	return
}

func (q *RequestParam) ParamBool(key string) (value bool, err error) {
	var (
		query string
	)
	if query, err = q.ParamString(key); err != nil {
		return false, err
	}
	if query == "1" || query == "true" || query == "True" {
		return true, nil
	}
	if query == "0" || query == "false" || query == "False" {
		return false, nil
	}
	return false, errors.New("转为Bool类型失败")
}

func (q *RequestParam) ParamJson(obj any) error {
	panic("implement me")
}
